package com.yc.demo.d0301;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

import static java.lang.System.out;

@WebServlet(name = "CookieServlet", value = "/CookieServlet")
public class CookieServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //获取Cookie数据
        final Cookie[] cookies = request.getCookies();
        //没有cookie数据，该数组为空
        final PrintWriter open = response.getWriter();
        if (cookies != null) {
            out.println("<url>");
            for (Cookie cookie: cookies) {
                out.printf("<li>%s : %s</li>",cookie.getName() + " "+cookie.getValue());
            }
            out.print("</ul>");
        }

        String name = request.getParameter("name");

        Cookie cookie = new Cookie("name", name);
        //有效期: 单位  秒  一周   有效期为 0 表示 删除该cookie
        if (name == null) {
            cookie.setMaxAge(0);
        }else {
            cookie.setMaxAge(60 * 60 * 24 * 7);
        }

        //cookie.setPath()  路径，默认当前路径
        //cookie.setDomain();  域名 => 同源策略

        //添加到相应对象中
        response.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
